package com.ptt.sqm.activity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.ksoap2.serialization.PropertyInfo;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.FragmentManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Context;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.ptt.sqm.component.Search;
import com.ptt.sqm.model.Login;
import com.ptt.sqm.session.CacheManager;
import com.ptt.sqm.session.SessionManager;
import com.ptt.sqm.util.AppUtil;
import com.ptt.sqm.ws.AsyncResponse;
import com.ptt.sqm.ws.DecrementCallback;
import com.ptt.sqm.ws.DefaultTask;
import com.ptt.sqmonmobile.R;
import com.ptt.sqmonmobile.TempActivity;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends DefaultActivity implements AsyncResponse, LoaderCallbacks<Cursor> {
	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */
	private DefaultTask mAuthTask;
	private static LoginActivity fragment;
	// UI references.
	private AutoCompleteTextView mUsernameView;
	private EditText mPasswordView;
	private View mProgressView;
	private View mLoginFormView;

	private int cnt;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		try {
			CacheManager.cacheData(getApplicationContext());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.i("CacheManager", e.toString());
		}
		
		if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
			// Activity was brought to front and not created,
			// Thus finishing this will get us to the last viewed activity
			finish();
			return;
		}

		// Set up the login form.
		mUsernameView = (AutoCompleteTextView) findViewById(R.id.username);

		mPasswordView = (EditText) findViewById(R.id.password);

		Button mSignInButton = (Button) findViewById(R.id.sign_in_button);
		mSignInButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				attemptLogin();
			}
		});

		mLoginFormView = findViewById(R.id.login_form);
		mProgressView = findViewById(R.id.login_progress);

	}

	private void populateAutoComplete() {
		getLoaderManager().initLoader(0, null, this);
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {
		if (mAuthTask != null) {
			return;
		}

		// Reset errors.
		mUsernameView.setError(null);
		mPasswordView.setError(null);

		// Store values at the time of the login attempt.
		String login = mUsernameView.getText().toString();
		String password = mPasswordView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password, if the user entered one.
		if (TextUtils.isEmpty(password)) {
			mPasswordView.setError(getString(R.string.error_invalid_password));
			focusView = mPasswordView;
			cancel = true;
		}

		// Check for a valid Login
		if (TextUtils.isEmpty(login)) {
			mUsernameView.setError(getString(R.string.error_field_required));
			focusView = mUsernameView;
			cancel = true;
		}

		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			showProgress(true);

			PropertyInfo userProp = new PropertyInfo();
			userProp.setName("login");
			userProp.setValue(login);
			userProp.setType(String.class);

			PropertyInfo passProp = new PropertyInfo();
			passProp.setName("password");
			passProp.setValue(password);
			passProp.setType(String.class);

			mAuthTask = new DefaultTask(com, getString(R.string.method_loginad));
			mAuthTask.delegate = this;
			mAuthTask.execute(userProp, passProp);
			// session.createLoginSession(getString(R.string.test_login_name),
			// getString(R.string.test_login_group));
			// Intent it = new Intent(getApplicationContext(),
			// MainActivity.class);
			// startActivity(it);

		}
	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	public void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

			mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
			mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
				@Override
				public void onAnimationEnd(Animator animation) {
					mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
				}
			});

			mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
			mProgressView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
				@Override
				public void onAnimationEnd(Animator animation) {
					mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
				}
			});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
			mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	@Override
	public void processFinish(String method, Object output) {
		// TODO Auto-generated method stub
		try {
			if (method.equals(getString(R.string.method_loginad)))
				getLoginAD(method, output);

		} catch (Exception e) {
		}
	}

	@Override
	public void processFinish(String method, Object output, Object... objects) {
		// TODO Auto-generated method stub

	}

	private void getLoginAD(String method, Object output) {
		// TODO Auto-generated method stub
		mAuthTask = null;
		Login login = new Login();
		try {
			login = gson.fromJson((String) output, Login.class);

			if (login.Result.equals(AppUtil.LOGIN_FAILED)) {
				showProgress(false);
				Toast.makeText(getApplicationContext(), login.Message, Toast.LENGTH_LONG).show();
			} else {
				// Login
				session.createLoginSession(login);

				// Search
				Search.reset();
				Search.getInstance(this, null, gson, com);

			}
		} catch (Exception e) {
			showProgress(false);
			Log.i("login", e.toString());
		}
	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		// TODO Auto-generated method stub

	}

}
